package com.ttg.common.utils;

import com.ttg.common.constant.FilePathConstant;
import com.ttg.common.vo.VerificateVO;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * 滑块验证码工具类
 */
public class CaptchaUtil {

    public static BufferedImage getFile(String dir) {

        BufferedImage bufferedImage = null;
        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            InputStream stream = resourceLoader.getResource("classpath:"+dir).getInputStream();
            bufferedImage = ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedImage;
    }

    public static VerificateVO getLoginCode() {
        // 随机选择需要切的图
        BufferedImage imgCatalog = getFile(FilePathConstant.LOGIN_BIG_IMAGE_PATH+ (new Random().nextInt(23) + 1) +".jpg");
        // 随机选择剪切模版
        BufferedImage tempImgFile = getFile(FilePathConstant.LOGIN_SMALL_IMAGE_PATH + (new Random().nextInt(6) + 1) + "-w.png");
        VerificateVO verificateVO = null;
        try {
            verificateVO = VerifyImageUtils.pictureTemplatesCut(tempImgFile, imgCatalog);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return verificateVO;
    }

}
